﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;

namespace Bing.Toolkit.Web
{
    /// <summary>
    /// Cookie操作类
    /// </summary>
    public static class CookieTool
    {
        /// <summary>
        /// 创建一个Cookie并赋值
        /// </summary>
        /// <param name="key">键</param>
        /// <param name="value">值</param>
        /// <param name="expires">有效期</param>
        /// <param name="domain">关联的域</param>
        public static void Set(string key, object value, DateTime? expires = null, string domain = "")
        {
            HttpCookie cookie = new HttpCookie(key, value.ToString());

            if (expires != null)
            {
                cookie.Expires = expires.Value;
            }

            if (!String.IsNullOrEmpty(domain))
            {
                cookie.Domain = domain;
            }

            HttpContext.Current.Response.Cookies.Add(cookie);
        }
        /// <summary>
        /// 根据键获取Cookie的值,并将值转化为对应的值类型
        /// </summary>
        /// <typeparam name="ReturnType">值类型</typeparam>
        /// <param name="key">键</param>
        /// <returns>值</returns>
        public static ReturnType Get<ReturnType>(string key)
        {
            try
            {
                HttpCookie cookie = HttpContext.Current.Request.Cookies[key];

                if (cookie == null)
                {
                    return default(ReturnType);
                }

                return (ReturnType)Convert.ChangeType(cookie, typeof(ReturnType));
            }
            catch
            {
                return default(ReturnType);
            }

        }
        /// <summary>
        /// 获取Cookie
        /// </summary>
        /// <param name="key">键</param>
        /// <returns></returns>
        public static HttpCookie GetCookie(string key)
        {
            return HttpContext.Current.Request.Cookies[key];
        }
    }
}
